package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登录管理
 */
@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //提交登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //用户名  密码
        if(StringUtils.isEmpty(userInfo.getLoginName())){
            return Result.fail().message("用户名不能为空");
        }
        if(StringUtils.isEmpty(userInfo.getPasswd())){
            return Result.fail().message("密码不能为空");
        }
        //返回用户的昵称 用户ID
        userInfo = userService.login(userInfo);
        //判断是否为NULL
        if(null != userInfo){
            //登录成功
            Map map = new HashMap<>();
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            //保存token 到缓存中 为了将来网关可以通过缓存来判断此用户的令牌是真还是假
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token,
                    userInfo.getId().toString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            map.put("token",token);
            map.put("nickName",userInfo.getNickName());
            return Result.ok(map);
        }else{
            //登录失败
            return Result.fail().message("用户名或密码不正确");
        }


        //return Result.ok();
    }
}
